package erfgame.frontend.desktop.view.terrain.iso.handler;

import java.awt.event.MouseEvent;
import java.util.List;

import erfgame.core.entity.Entity;
import erfgame.core.graphics.renderer.chain.RendererChain;
import erfgame.core.world.terrain.insertion.SurfaceInsertion;

import erfgame.frontend.desktop.view.terrain.iso.EntitySelection;
import erfgame.frontend.desktop.view.terrain.iso.IsometricTerrainView;

public class EntitySelectionInteractionHandler 
	extends BaseInteractionHandler {

	private EntitySelection selection;
	private MouseEvent mouseDownEvent;
	private IsometricTerrainView view;
	
	public EntitySelectionInteractionHandler( 
			EntitySelection selection,
			IsometricTerrainView view 
	) {
		this.selection = selection;
		this.view = view;
	}

	@Override
	public MouseEvent[] handleMouseEvent(MouseEvent e) {
		MouseEvent[] result;
		switch( e.getID() ){
		case MouseEvent.MOUSE_PRESSED:
			if(e.getButton() == MouseEvent.BUTTON1) {
				this.mouseDownEvent = e;
				result = null;
			} else {
				result = super.handleMouseEvent(e);
			}
			break;
		case MouseEvent.MOUSE_RELEASED:
			if(e.getButton() == MouseEvent.BUTTON1 && this.mouseDownEvent != null) {
				this.mouseDownEvent = null;
				result = null;
				// select first entity
				select(e.getX(), e.getY());
			} else {
				result = super.handleMouseEvent(e);
			}
			break;
		case MouseEvent.MOUSE_DRAGGED:
			if( this.mouseDownEvent != null ) {
				result = new MouseEvent[]{this.mouseDownEvent,e};
				this.mouseDownEvent = null;
			} else {
				result = super.handleMouseEvent(e);
			}
			break;
		default:
			result = super.handleMouseEvent(e);
		}
		return result;
	}
	
	public void select( int x, int y ) {
		List<SurfaceInsertion> insertions = view.getInsertionsAt(x, y);
		if( insertions != null ) {
			while( insertions.size() > 0 ) {
				SurfaceInsertion insertion = insertions.remove(0);
				RendererChain rendererChain = insertion.getRendererChain();
				Entity entity = rendererChain.getHead().getEntity();
				if( entity != null ) {
					selection.clear();
					selection.addRendererChain( rendererChain, view.getCurrentRotation() );
					break;
				}								
			}
		}
	}
	
}
